package com.System.servlet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class BaseServlet extends HttpServlet {
    //重写service方法使之能够获取请求行的数据来进行方法分发
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.h获取请求路径
        String requestURI = req.getRequestURI();//uri是比较短的
        //获取最后一段路径即方法名
        int index=requestURI.lastIndexOf('/');
        String methodName=requestURI.substring(index+1);
        //获取调用者的字节码文件就是class文件
        Class<? extends BaseServlet> cls = this.getClass();
        //获取方法对象
        try {
            //获取方法对象
            Method method = cls.getMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
            //执行方法
            try {
                method.invoke(this,req,resp);
            } catch (IllegalAccessException e) {
                throw new RuntimeException(e);
            } catch (InvocationTargetException e) {
                throw new RuntimeException(e);
            }
        } catch (NoSuchMethodException e) {
            throw new RuntimeException(e);
        }


    }
}
